package com.example.puzzlegame.Utils;

import android.graphics.Bitmap;

import com.example.puzzlegame.Page.PuzzlePage;


import java.util.ArrayList;
import java.util.List;

//拼图工具类：实现拼图的交换与生成算法
public class GameUtil {

    public static List<ImgBean> mImgBeans = new ArrayList<>();//游戏信息 单元格Bean
    public static Bitmap mLastBitmap;   //拼图完成时显示的最后一个图片
    public static ImgBean mBlankImgBean;//空格单元格
    public static int blankPosition = -1;


    //是否可以完成拼图，拼图算法的判断
    public static boolean canSolve(List<Integer> list){
        //获取空格ID
        int blankId = mBlankImgBean.getmItemId();
        //可行性判断
        if(list.size() % 2 ==1) {//序列长度为奇数
            return getInversion(list) % 2 == 0;
        } else {//序列长度为偶数

            if(((blankId -1)/ PuzzlePage.GAME_TYPE)%2 == 1){//从底往上数,空格位于奇数行
                return getInversion(list)%2 == 0;
            }else{//从底往上数,空格位于偶数行

                return getInversion(list)%2 == 1;
            }
        }
    }

    //交换空格与碎片的位置
    public static void swapItems(ImgBean form, ImgBean blank){//form为交换格，blank为空白格
        ImgBean tempImgBean = new ImgBean();

        // 交换BitmapId
        tempImgBean.setmBitmapId(form.getmBitmapId());//temp
        form.setmBitmapId(blank.getmBitmapId());
        blank.setmBitmapId(tempImgBean.getmBitmapId());
        // 交换Bitmap
        tempImgBean.setmBitmap(form.getmBitmap());  //temp
        form.setmBitmap(blank.getmBitmap());
        blank.setmBitmap(tempImgBean.getmBitmap());
        // 设置新的Blank
        com.example.puzzlegame.Utils.GameUtil.mBlankImgBean = form;
    }


    //生成随机的item(打乱初始状态)
    public static void getPuzzleGenertor(){
        int index = 0;

        for(int i=0; i<mImgBeans.size() * 2; i++){  //有1/2概率可能生成无解的序列
            index = (int)(Math.random() * PuzzlePage.GAME_TYPE * PuzzlePage.GAME_TYPE);//生成一定范围内的随机数作为form的标识符[0，9)
            swapItems(mImgBeans.get(index), com.example.puzzlegame.Utils.GameUtil.mBlankImgBean);
        }

        blankPosition = index ;//记录空白块位置，便于计算序列是否有解

        List<Integer> list = new ArrayList<>();

        for (int i=0; i<mImgBeans.size(); i++){
            list.add(mImgBeans.get(i).getmBitmapId());//存储当前id序列
        }

        // 判断生成是否有解
        if (canSolve(list)){
            return;
        } else {
            getPuzzleGenertor();
        }
    }

    //计算逆序算法
    private static int getInversion(List<Integer> list){
        int inversion = 0;
        int inversionCount = 0;

        for (int i=0; i<list.size(); i++){
            for(int j=i+1; j<list.size(); j++){
                int index = list.get(i);
                if(list.get(j) != 0 && list.get(j) < index) {
                    inversionCount++;   //逆序对个数+1
                }
            }
            inversion += inversionCount;    //逆序对总数
            inversionCount = 0;
        }
        return inversion;
    }
}
